package com.kede.api.stand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kede.api.ienum.VipEnum;
import com.kede.api.stand.pub.AreaInfoVo;
import com.kede.api.stand.service.IUserManageService;
import com.kede.api.stand.service.SysAreaService;
import com.kede.api.stand.utils.GaoDeMapUtil;
import com.kede.domain.ConfigDomain;
import com.kede.domain.UsersDomain;
import com.kede.domain.ZhiOrderGoodsListDomain;
import com.kede.ienum.zhi.ZhiOrderStatusEnum;
import com.kede.pojo.ResHttp;
import com.kede.service.ConfigService;
import com.kede.service.UsersService;
import com.kede.service.ZhiOrderGoodsListService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:Pr.li
 * @Date: create in 2023/6/26 21:12
 */
@Service
public class UserManageServiceImpl implements IUserManageService {

    @Resource
    private UsersService usersService;

    @Resource
    private ConfigService configService;

    @Resource
    private ZhiOrderGoodsListService zhiOrderGoodsListService;

    @Resource
    private SysAreaService sysAreaService;

    @Override
    public ResHttp getUserCanZhiNum(Integer userid) {
        UsersDomain user = usersService.getById(userid);
        Map<String,Number> result = new HashMap<>();
        if (user == null){
            return ResHttp.failMsg("用户不存在");
        }
        if (user.getIsVip().equals(VipEnum.Vip2.getValue())){
            //剩余置换数 -1无限制
            result.put("residue_num",-1);
        }else {
            LambdaQueryWrapper<ConfigDomain> configQuery = new LambdaQueryWrapper<>();
            configQuery.eq(ConfigDomain::getName, "unit_num");
            ConfigDomain one = configService.getOne(configQuery);
            Integer unit_num = Integer.valueOf(one.getValue());


//            用户这个月兑换过的件数
            LambdaQueryWrapper<ZhiOrderGoodsListDomain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZhiOrderGoodsListDomain::getUserId,userid);
            queryWrapper.eq(ZhiOrderGoodsListDomain::getDefaultUserMoney,"0");
            int count = getCount( queryWrapper,user.getYetNum());
            //剩余置换数
            if(unit_num <= count){
                result.put("residue_num", 0);
            }else{
                result.put("residue_num", unit_num - count);
            }

        }
        result.put("vip",user.getIsVip());
        return ResHttp.okData(result);
    }

    @Override
    public ResHttp getUserMoneyOrderCanZhiNum(Integer userid) {
        UsersDomain user = usersService.getById(userid);
        Map<String,Number> result = new HashMap<>();
        ConfigDomain one = configService.getOneByName("money_unit_num");
        Integer unit_num = Integer.valueOf(one.getValue());
        if (user == null){
            return ResHttp.failMsg("用户不存在");
        }
        if (unit_num.equals("-1") ||user.getIsVip().equals(VipEnum.Vip2.getValue())){
            //剩余置换数 -1无限制
            result.put("residue_num",-1);
        }else {
//            用户这个月兑换过的件数
            LambdaQueryWrapper<ZhiOrderGoodsListDomain> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZhiOrderGoodsListDomain::getUserId, userid);
            queryWrapper.gt(ZhiOrderGoodsListDomain::getDefaultUserMoney,"0");
            int count = getCount( queryWrapper,user.getZhiMoneyNum());
            //剩余置换数
            if(unit_num <= count){
                result.put("monty_residue_num", 0);
            }else{
                result.put("monty_residue_num", unit_num - count);
            }

        }
        result.put("vip",user.getIsVip());
        return ResHttp.okData(result);
    }

    @Override
    public ResHttp upAddressByUserId(Integer userId, String lng, String lat) {
        UsersDomain byId = usersService.getById(userId);
        if(byId != null){
            if(byId.getAddress().equals(0)){
                try{
                    GaoDeMapUtil.AddressComponentDto addressComponentByLocation = GaoDeMapUtil.getAddressComponentByLocation(lng, lat);
                    byId.setAddress(addressComponentByLocation.getAdcode());
                    usersService.updateById(byId);
                }catch (Exception e){
                    return ResHttp.fail();
                }
            }else if(byId.getProvinceCode().equals(0)){
                AreaInfoVo detailByAdcode = sysAreaService.findDetailByAdcode(byId.getAddress());
                byId.setProvinceCode(detailByAdcode.getProvinceCode());
                byId.setCityCode(detailByAdcode.getCityCode());
                usersService.updateById(byId);
            }

        }
        return ResHttp.ok();
    }

    private int getCount(LambdaQueryWrapper<ZhiOrderGoodsListDomain> queryWrapper,Integer haveCount) {
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime firstdaytime =  date.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime lastdaytime = date.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        //大于等于
        queryWrapper.ge(ZhiOrderGoodsListDomain::getCreatetime,firstdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
//            小于等于
        queryWrapper.le(ZhiOrderGoodsListDomain::getCreatetime,lastdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
        queryWrapper.and(zhiOrderGoodsListDomainLambdaQueryWrapper -> {
            zhiOrderGoodsListDomainLambdaQueryWrapper.eq(ZhiOrderGoodsListDomain::getStatus,ZhiOrderStatusEnum.ING.getCode())
                    .or().eq(ZhiOrderGoodsListDomain::getStatus,ZhiOrderStatusEnum.WAIT.getCode());
        });
        //这个月已经兑换的除了拒绝的数量
        int count = zhiOrderGoodsListService.count(queryWrapper) + haveCount;
        return count;
    }

    /**
     * 获取用户已经置换的数量
     * @param queryWrapper
     * @return
     */
    @Override
    public int getCountZhiOrderGooded(LambdaQueryWrapper<ZhiOrderGoodsListDomain> queryWrapper) {
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime firstdaytime =  date.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime lastdaytime = date.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        //大于等于
        queryWrapper.ge(ZhiOrderGoodsListDomain::getCreatetime,firstdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
//            小于等于
        queryWrapper.le(ZhiOrderGoodsListDomain::getCreatetime,lastdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
        queryWrapper.and(zhiOrderGoodsListDomainLambdaQueryWrapper -> {
            zhiOrderGoodsListDomainLambdaQueryWrapper.eq(ZhiOrderGoodsListDomain::getStatus,ZhiOrderStatusEnum.ING.getCode())
                    .or().eq(ZhiOrderGoodsListDomain::getStatus,ZhiOrderStatusEnum.WAIT.getCode())
                    .or().eq(ZhiOrderGoodsListDomain::getStatus,ZhiOrderStatusEnum.FINISH.getCode());
        });
        //这个月已经兑换的除了拒绝的数量
        int count = zhiOrderGoodsListService.count(queryWrapper);
        return count;
    }

    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();
        LocalDateTime firstdaytime =  date.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime lastdaytime = date.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        System.out.println(firstdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
        System.out.println(lastdaytime.toEpochSecond(ZoneOffset.ofHours(8)));
    }


}
